package top.broncho.mvvm.util

import top.broncho.gank.constant.Constant
import okhttp3.Call
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import org.jetbrains.anko.warn

const val DOMAIN_NAME = "Domain-Name"

class CallFactoryProxy(private val delegate: Call.Factory) : Call.Factory, AnkoLogger {

    override fun newCall(request: Request): Call {
        val newBaseUrl = request.header(DOMAIN_NAME)
        if (newBaseUrl != null) {
            val oldUrl = request.url.toString()
            val newUrl = oldUrl.replace(Constant.BASE_URL.toRegex(), newBaseUrl)
            info { "newCall: oldUrl = $oldUrl, newUrl = $newUrl" }
            val newRequest = request.newBuilder().url(newUrl.toHttpUrl()).build()
            return delegate.newCall(newRequest)
        } else {
            warn { "newCall: return null when newBaseUrl is null!" }
        }
        return delegate.newCall(request)
    }

}
